package com.my.study.aqs;

import com.my.study.utils.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Carlos
 * @version 1.0
 * @Description 数据容器
 * @date 2021/6/17 8:10
 **/
@Slf4j(topic = "c.DataContainer")
public class DataContainer {

    private Object data;
    private ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.ReadLock readLock = rw.readLock();
    private ReentrantReadWriteLock.WriteLock writeLock = rw.writeLock();


    public Object read() {
        log.debug("获取读锁...");
        readLock.lock();
        try {
            log.debug("读取操作...");
            ThreadUtil.sleep(1);
            return data;
        } finally {
            readLock.unlock();
            log.debug("释放读锁...");
        }
    }

    public void write(Object data) {
        log.debug("获取写锁...");
        writeLock.lock();
        try {
            log.debug("写入操作...");
            this.data = data;
        } finally {
            writeLock.unlock();
            log.debug("释放写锁...");
        }
    }

}
